package com.group.service;

import com.group.dao.GeneralBeanDao;
import com.group.dao.LotteryDao;
import com.group.model.*;
import com.group.util.NoteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;

@Service
public class LotteryService {

    Logger logger = LoggerFactory.getLogger(LotteryService.class);

    @Autowired
    LotteryDao lotteryDao;
    @Autowired
    GeneralBeanDao beanDao;
    @Autowired
    TickerService tickerService;

    /**
     * 根据Math.random()产生一个double型的随机数，判断每个奖品出现的概率
     * @param prizes
     * @return random：奖品列表prizes中的序列（prizes中的第random个就是抽中的奖品）
     */
    public static int getPrizeIndex(List<LotteryPrize> prizes) {
        DecimalFormat df = new DecimalFormat("######0.00");
        int random = -1;
        try{
            //计算总权重
            double sumWeight = 0;
            for(LotteryPrize p : prizes){
                sumWeight += p.getPrizeWeight();
            }

            //产生随机数
            double randomNumber;
            randomNumber = Math.random();

            //根据随机数在所有奖品分布的区域并确定所抽奖品
            double d1 = 0;
            double d2 = 0;
            for(int i=0;i<prizes.size();i++){
                d2 += Double.parseDouble(String.valueOf(prizes.get(i).getPrizeWeight()))/sumWeight;
                if(i==0){
                    d1 = 0;
                }else{
                    d1 +=Double.parseDouble(String.valueOf(prizes.get(i-1).getPrizeWeight()))/sumWeight;
                }
                if(randomNumber >= d1 && randomNumber <= d2){
                    random = i;
                    break;
                }
            }
        }catch(Exception e){
            System.out.println("生成抽奖随机数出错，出错原因：" +e.getMessage());
        }
        return random;
    }

    /**
     * 抽奖
     * @param userId
     * @param multiple
     * @return
     */
    @Transactional
    public LotteryPrize doLottery(Long userId, Integer multiple) {
        ActUser au = beanDao.quickQueryOne(ActUser.class,"userId", userId);
        if(au == null){
            throw new NoteException("怎么可能！");
        }
        Long now = System.currentTimeMillis();
        List<LotteryPrize> prizes = lotteryDao.findAll();
        int selected = getPrizeIndex(prizes);
        System.out.println("抽中的奖品为 >>>>" + prizes.get(selected).getId());
        LotteryPrize lp = beanDao.quickQueryOne(LotteryPrize.class, "id", prizes.get(selected).getId());
        if(lp == null){
            throw new NoteException("抽奖系统出错！");
        }
        WinningRecord wr = new WinningRecord();
        if(au.getTimes()>0){//免费次数
            if(multiple != 1){
                throw new NoteException("免费次数不能选择倍数！");
            }
            //减次数
            au.setTimes(au.getTimes() - 1);
            beanDao.save(au);
            //谢谢惠顾
            if(lp.getId().equals(1)){
                return lp;
            }
            UserTicker ut = beanDao.quickQueryOne(UserTicker.class, "userId", userId);
            if(ut == null){
              throw new NoteException("钱包异常！没有钱包数据");
            }
            tickerService.addTicker(userId, "wecc", lp.getPrizeFee()*multiple, "抽奖奖励");
            wr.setPayMethod(0);
        }else if (au.getTimes().equals(0)) { //用WECC抽奖
            //修改用户余额并添加流水记录
            UserTicker ut = beanDao.quickQueryOne(UserTicker.class, "userId", userId);
            Double s = Double.parseDouble(beanDao.quickQueryOne(SystemPara.class, "name", "lotteryCost").getValue());
            Double num = ut.getNum();
            if(ut.getNum() < s * multiple){
                throw new NoteException("您的余额不足!");
            }
            //谢谢惠顾
            if(lp.getId().equals(1)){
                tickerService.addTicker(userId, "wecc", -s*multiple, "抽奖消耗");
                return lp;
            }
            //钱包金额减去抽奖消耗加上奖金
            User u = beanDao.quickQueryOneById(User.class, userId);
            tickerService.addTicker(userId, "wecc", - s * multiple, "抽奖消耗");
            tickerService.addTicker(userId, "wecc", multiple * lp.getPrizeFee(), "抽奖奖励");
            wr.setPayMethod(1);
        }else{
            System.out.println("7777777777777777777777777777777777777777777777777777777777777777777777777777");

        }
        //保存中奖纪录
        wr.setCreateDate(now);
        wr.setUserId(userId);
        wr.setMultiple(multiple);
        if (lp.getPrizeName().contains("WECC")) {
            wr.setFee(lp.getPrizeFee()*multiple);
            beanDao.save(wr);
        } else {//如果是除WECC以外的奖品do↓
            wr.setFee(0.0);
            wr.setData(lp.getPrizeName());
            beanDao.save(wr);
            return lp;
        }
        return lp;
    }

    /**
     * 获得喇叭
     * @param limit
     * @return
     */
    public List<String> getHorn(Integer limit){
        List<WinningRecord> list = lotteryDao.getHorn(limit);
        List<String> mes = new ArrayList<>();
        list.forEach( s -> {
            if(s.getFee() != 0.0){
                String msg = String.format("恭喜用户%s抽中%sWECC",beanDao.quickQueryOneById(User.class, s.getUserId()).getTel(),s.getFee());
                mes.add(msg);
            }else if(!s.getData().contains("谢谢")){
                String msg = String.format("恭喜用户%s抽中%s",beanDao.quickQueryOneById(User.class, s.getUserId()).getTel(),s.getData());
                mes.add(msg);
            }
        });
        return mes;
    }


    public void updatelt(){
        logger.debug("=======================================Get it=====================================================");
        int i = Integer.parseInt(beanDao.quickQueryOne(SystemPara.class, "name", "lotteryTimes").getValue());
        logger.debug("=====================================systemParam:====="+i+"===================================================");
        int a = lotteryDao.updateTimes(i);
        int b = lotteryDao.updateshareTimes();
        logger.debug(String.format("次数：%s,分享次数：%s", a, b));
    }
}